# -*- coding: utf-8 -*-
"""
Created on Mon May 10 20:25:32 2021

@author: Administrator
"""
import pandas as pd
import numpy as np

# 读取数据
option_price = pd.read_feather("./data/optionprice.feather")
stock_price = pd.read_feather("./data/stockprice.feather")

option_price['Date'] = pd.to_datetime(option_price.Date,format="%Y-%m-%d")
option_price['Expiration'] = pd.to_datetime(option_price.Expiration,format="%Y-%m-%d")
option_price.loc[:,'time2mat'] =(pd.eval("option_price.Expiration-option_price.Date")).dt.days

# 也是不能对数据进行筛选的额
#option_price = option_price[option_price['SecurityID']==106445]
#%%
from utils import EMA,get_option_greek,get_option_price

stock_price_ = pd.DataFrame([],columns=['SecurityID','Date','Price','RV'])
decay_rate =0.96
time_period = 60

r = 0.0335
vols = []
# 使用EMA计算了历史波动率的值
stocks = stock_price['SecurityID'][~(stock_price['SecurityID'].duplicated())]
for stock in stocks:
    
    stock_info = stock_price[['SecurityID','Date','Price']][stock_price['SecurityID']==stock]  
    vol = EMA(stock_info['Price'],decay_rate,time_period)
    stock_info.loc[:,'RV'],_,_ = EMA(stock_info['Price'],decay_rate,time_period)
    stock_price_ = stock_price_.append(stock_info)
    vols.append(vol)
    
    
# 感觉并不能用简单的聚合计算代替
stock_price_['Date'] = pd.to_datetime(stock_price_.Date,format="%Y-%m-%d")    
    
#%%
# 使用BS公式算期权每天的希腊值和价格
stock_option = pd.merge(option_price,stock_price_[['SecurityID','Date','Price','RV']],how='inner',on=['SecurityID','Date'])
for idx,option in stock_option.iterrows():
    stock = option['SecurityID']
    date = option['Date']
    IV = option['RV'].values[0]*1.2
    if option['Delta'] == -99:
        stock_option.loc[idx,'adj_delta'] =-99
        stock_option.loc[idx,'option_value'] = -99
    if IV > 0:
        stock_option.loc[idx,'adj_delta'] = get_option_greek(option['Price'], option['Strike']/1000, r, IV, option['time2mat']/365, option['CallPut'])['delta']
        stock_option.loc[idx,'option_value'] =get_option_price(option['Price'], option['Strike']/1000, r, IV, option['time2mat']/365, option['CallPut']) 
        
# 计算delta和价格直接放到option对冲的地方去，不要放在这里计算。
        
    



